import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons'
import {
  App,
  Col,
  DatePicker,
  Form,
  Input,
  Popover,
  Radio,
  Row,
  Segmented,
  Select,
  Space,
} from 'antd'
import { SegmentedValue } from 'antd/es/segmented'
import dayjs from 'dayjs'
import Image from 'next/image'
import { useRouter } from 'next/router'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'

import { EnumsRes, Violation } from '@/api/interface'
import { UploadFile } from '@/api/modules/entity'
import alert from '@/assets/images/alert-circle.png'
import arrowNext from '@/assets/images/arrow-next.png'
import arrowPre from '@/assets/images/arrow-pre.png'
import close from '@/assets/images/close.png'
import del from '@/assets/images/delete.png'
import file from '@/assets/images/file.png'
import styles from '@/pages/entityForm/styles/index.module.less'

const { TextArea } = Input

const fileTypes = [
  'image/pjpeg',
  'image/jpeg',
  'image/png',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'application/pdf',
]

interface Props {
  t: any
  lang: string
  enums: { [key: string]: EnumsRes[] }
  setSetup: Dispatch<SetStateAction<number>>
  violation: Partial<Violation>
  setViolation: Dispatch<SetStateAction<Partial<Violation>>>
}

export default function ComplaintDetails({
  t,
  lang,
  enums,
  setSetup,
  violation,
  setViolation,
}: Props) {
  const router = useRouter()
  const [form] = Form.useForm()

  const { message } = App.useApp()

  const [report, setReport] = useState<boolean>()

  useEffect(() => {
    if (violation.type) setType(violation.type)
    form.setFieldsValue(violation)
    setReport(violation.hasReported)
  }, [])

  const [type, setType] = useState<SegmentedValue>('A')
  const changeType = (value: SegmentedValue) => {
    setType(value)
  }

  const onFinish = (values: Partial<Violation>) => {
    setViolation({
      ...violation,
      ...values,
      type: type,
      violationDate: dayjs(values.violationDateValue).format('DD/MM/YYYY'),
      incidentDiscoveredDate: dayjs(values.incidentDiscoveredDateValue).format('DD/MM/YYYY'),
      refYear: dayjs(values.complianceDateValue).format('DD/MM/YYYY'),
      // refMonth: dayjs(values.complianceDateValue).format('MM'),
    })
    setSetup(2)
  }

  const Alert = ({ text }: { text: string }) => {
    return (
      <Popover placement={lang === 'en-US' ? 'right' : 'left'} content={text}>
        <Image src={alert} alt="alert" className={styles['form-alert-icon']}></Image>
      </Popover>
    )
  }

  const FormLabel = ({
    title,
    alert,
    required = true,
    small = false,
  }: {
    title: string
    alert?: string
    required?: boolean
    small?: boolean
  }) => {
    return (
      <div className={small ? styles['form-item-label-small'] : styles['form-item-label']}>
        <span className={styles['form-item-label-text']}>{title}</span>
        {required && <span className={styles['form-item-label-required']}>*</span>}
        {alert && <Alert text={alert} />}
      </div>
    )
  }

  const FileUploadComponent = () => {
    const fileInputRef = useRef<HTMLInputElement | null>(null)
    const handleFileSelect = () => {
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
        fileInputRef.current.click()
      }
    }

    const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
      const files = e.target.files
      if (files?.length! > 5)
        return message.warning(t['form.complaint.attachments.upload.length.warning'])
      if (files) {
        const uploadPromises = Array.from(files).map(async (file) => {
          const imgType = fileTypes.includes(file.type)
          const imgSize = file.size / 1024 / 1024 < 200
          if (!imgType) {
            message.warning(t['form.complaint.attachments.upload.type.warning'])
            return null
          }
          if (!imgSize) {
            message.warning(t['form.complaint.attachments.upload.size.warning'])
            return null
          }

          const excelFormData = new FormData()
          excelFormData.append('file', file)
          const { data } = await UploadFile(excelFormData)
          return { desc: '', href: data, id: '' }
        })

        const uploadedFiles = await Promise.all(uploadPromises)

        // Filter out null values (warnings) and update the state with uploaded files
        const filteredFiles = uploadedFiles.filter(
          (file) => file !== null
        ) as Violation['supportEntities']

        setViolation({
          ...violation,
          supportEntities: [...violation.supportEntities!, ...filteredFiles],
        })
      }
    }

    const delFile = (file: string) => {
      setViolation({
        ...violation,
        supportEntities: violation.supportEntities?.filter((item) => item.href !== file),
      })
    }

    return (
      <>
        {violation.supportEntities?.length ? (
          <div className={styles['form-complaint-file']}>
            {violation.supportEntities?.map((item) => {
              return (
                <div className={styles['form-complaint-file-item']} key={item.href}>
                  <Image src={file} className={styles['file-icon']} alt="file" />
                  <span className={styles['file-text']}>{item.href}</span>
                  <Image
                    onClick={() => delFile(item.href)}
                    src={close}
                    className={styles['file-close']}
                    alt="close"
                  />
                </div>
              )
            })}
          </div>
        ) : (
          <></>
        )}

        <div className={styles['form-complaint-add']}>
          <span onClick={handleFileSelect}>{t['form.complaint.attachments.upload']}</span>
          <input
            type="file"
            multiple
            style={{ display: 'none' }}
            ref={fileInputRef}
            onChange={handleFileUpload}
            accept=".jpeg,.png,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf"
          />
        </div>
      </>
    )
  }
  const disabledDate = (current: any) => {
    return current && current > dayjs().endOf('day')
  }

  return (
    <div className={styles['form-complaint']}>
      <h2 className={styles['form-title-h3']}>{t['form.complaint.title']}</h2>
      <Form layout="vertical" name="complaint" form={form} onFinish={onFinish}>
        <Row gutter={24}>
          <Col xs={24} className={styles['form-complaint-segmented']}>
            <Segmented
              value={type}
              options={[
                { label: t['form.complaint.violation.typeA'], value: 'A' },
                { label: t['form.complaint.violation.typeB'], value: 'B' },
              ]}
              size="large"
              onChange={changeType}
            />
            <span className={styles['form-item-label-required']}>*</span>
            <Alert
              text={
                type === 'A'
                  ? t['form.complaint.violation.typeA.extra']
                  : t['form.complaint.violation.typeB.extra']
              }
            />
          </Col>
          {type === 'A' ? (
            <Col xs={24}>
              <Form.Item label={''}>
                <Form.Item
                  name="violationTypeA"
                  rules={[{ required: true, message: t['form.complaint.violation.error'] }]}
                >
                  <Select
                    options={enums.ViolationTypeA.map((item) => ({
                      value: item?.key,
                      label: item?.value[lang === 'en-US' ? 'en' : 'ar'],
                    }))}
                    className="multiple-select"
                    mode="multiple"
                    maxTagCount="responsive"
                    allowClear
                    showSearch
                    optionFilterProp="label"
                    placeholder={t['form.complaint.violation.placeholder']}
                    suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                  />
                </Form.Item>
              </Form.Item>
            </Col>
          ) : (
            <Col xs={24}>
              <Form.Item label={''}>
                <Form.Item
                  name="violationTypeB"
                  rules={[{ required: true, message: t['form.complaint.violation.error'] }]}
                >
                  <Select
                    options={enums.ViolationTypeB.map((item) => ({
                      value: item?.key,
                      label: item?.value[lang === 'en-US' ? 'en' : 'ar'],
                    }))}
                    className="multiple-select"
                    mode="multiple"
                    maxTagCount="responsive"
                    allowClear
                    showSearch
                    optionFilterProp="label"
                    placeholder={t['form.complaint.violation.placeholder']}
                    suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                  />
                </Form.Item>
              </Form.Item>
            </Col>
          )}
          <Col span={24}>
            <Form.Item
              label={
                <FormLabel
                  title={t['form.complaint.violationDate']}
                  alert={t['form.complaint.violationDate.extra']}
                  required={false}
                />
              }
            >
              <Form.Item name="violationDateValue">
                <DatePicker
                  disabledDate={disabledDate}
                  format={'DD/MM/YYYY'}
                  style={{ width: '200px' }}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              label={
                <FormLabel
                  title={t['form.complaint.description']}
                  alert={t['form.complaint.description.extra']}
                />
              }
            >
              <Form.Item
                name="violationDesc"
                rules={[{ required: true, message: t['form.complaint.description.error'] }]}
              >
                <TextArea
                  rows={4}
                  showCount
                  maxLength={5000}
                  placeholder={t['form.complaint.description.placeholder']}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label={<FormLabel title={t['form.complaint.incidentDate']} />}>
              <Form.Item
                name="incidentDiscoveredDateValue"
                rules={[{ required: true, message: t['form.complaint.incidentDate.error'] }]}
              >
                <DatePicker
                  disabledDate={disabledDate}
                  format={'DD/MM/YYYY'}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label={<FormLabel title={t['form.complaint.reported']} />}>
              <Form.Item
                name="hasReported"
                rules={[{ required: true, message: t['form.complaint.reported.error'] }]}
              >
                <Radio.Group
                  size="large"
                  onChange={(e) => {
                    setReport(e.target.value)
                  }}
                >
                  <Radio value={true}> {t['form.complaint.reported.radio.yes']} </Radio>
                  <Radio value={false}> {t['form.complaint.reported.radio.no']} </Radio>
                </Radio.Group>
              </Form.Item>
            </Form.Item>
          </Col>
          {report ? (
            <>
              <Col md={8} xs={24}>
                <Form.Item label={<FormLabel title={t['form.complaint.entityName']} />}>
                  <Form.Item
                    name="refEntity"
                    rules={[{ required: true, message: t['form.complaint.entityName.error'] }]}
                  >
                    <Input maxLength={100} placeholder={t['form.complaint.entityName']} />
                  </Form.Item>
                </Form.Item>
              </Col>
              <Col md={8} xs={24}>
                <Form.Item
                  label={<FormLabel title={t['form.complaint.reference']} required={false} />}
                >
                  <Form.Item name="refRefNumber">
                    <Input maxLength={200} placeholder={t['form.complaint.reference']} />
                  </Form.Item>
                </Form.Item>
              </Col>
              <Col md={8} xs={24}>
                <Form.Item
                  label={<FormLabel title={t['form.complaint.complianceDate']} required={false} />}
                >
                  <Form.Item name="complianceDateValue">
                    <DatePicker
                      disabledDate={disabledDate}
                      // picker="month"
                      format={'DD/MM/YYYY'}
                      style={{ width: '100%' }}
                      // placeholder={t['form.complaint.complianceDate.placeholder']}
                    />
                  </Form.Item>
                </Form.Item>
              </Col>
            </>
          ) : (
            <></>
          )}
          <Col span={24}>
            <Form.Item
              label={
                <FormLabel
                  title={t['form.complaint.additional']}
                  alert={t['form.complaint.additional.extra']}
                  required={false}
                />
              }
            >
              <Form.Item name="violationAdditionalDetails">
                <TextArea
                  rows={4}
                  showCount
                  maxLength={5000}
                  placeholder={t['form.complaint.additional.placeholder']}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24} className={styles['form-complaint-witnesses']}>
            <Form.Item label={<FormLabel title={t['form.complaint.witnesses']} required={false} />}>
              <Form.List name="violators">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <Space key={key} size={24}>
                        <Form.Item
                          label={
                            <FormLabel title={t['form.complaint.witnesses.name']} small={true} />
                          }
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'concernedParties']}
                            rules={[
                              { required: true, message: t['form.complaint.witnesses.name.error'] },
                            ]}
                          >
                            <Input
                              maxLength={200}
                              placeholder={t['form.complaint.witnesses.placeholder.input']}
                            />
                          </Form.Item>
                        </Form.Item>
                        <Form.Item
                          label={
                            <FormLabel title={t['form.complaint.witnesses.role']} small={true} />
                          }
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'role']}
                            rules={[
                              { required: true, message: t['form.complaint.witnesses.role.error'] },
                            ]}
                          >
                            <Select
                              options={enums.ViolatorOrWitness.map((item) => ({
                                value: item.key,
                                label: item.value[lang === 'en-US' ? 'en' : 'ar'],
                              }))}
                              allowClear
                              showSearch
                              optionFilterProp="label"
                              placeholder={t['form.complaint.witnesses.placeholder.select']}
                              suffixIcon={
                                lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />
                              }
                            />
                          </Form.Item>
                        </Form.Item>
                        <Form.Item
                          label={
                            <FormLabel
                              title={t['form.complaint.witnesses.nationality']}
                              required={true}
                              small={true}
                            />
                          }
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'nationality']}
                            rules={[
                              {
                                required: true,
                                message: t['form.complaint.witnesses.nationality.error'],
                              },
                            ]}
                          >
                            <Select
                              options={enums.Nationality.map((item) => ({
                                value: item.key,
                                label: item.value[lang === 'en-US' ? 'en' : 'ar'],
                              }))}
                              allowClear
                              showSearch
                              optionFilterProp="label"
                              placeholder={t['form.complaint.witnesses.placeholder.select']}
                              suffixIcon={
                                lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />
                              }
                            />
                          </Form.Item>
                        </Form.Item>
                        <Image
                          onClick={() => remove(name)}
                          src={del}
                          className={styles['form-complaint-witnesses-del']}
                          alt="del"
                        />
                      </Space>
                    ))}
                    <Form.Item>
                      <span
                        onClick={() => add()}
                        className={styles['form-complaint-witnesses-add']}
                      >
                        {t['form.complaint.witnesses.add']}
                      </span>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              label={
                <FormLabel
                  title={t['form.complaint.attachments']}
                  alert={t['form.complaint.attachments.extra']}
                  required={false}
                />
              }
            >
              <Form.Item>
                <FileUploadComponent />
              </Form.Item>
            </Form.Item>
          </Col>
        </Row>
        <div className={styles['form-button']}>
          <div className={styles['form-button-pre']} onClick={() => router.back()}>
            <Image src={arrowPre} className={styles['button-icon']} alt="pre" />
            <span className={styles['button-text']}>{t['form.button.back']}</span>
          </div>
          <div className={styles['form-button-next']} onClick={() => form.submit()}>
            <span className={styles['button-text']}>{t['form.button.next']}</span>
            <Image src={arrowNext} className={styles['button-icon']} alt="next" />
          </div>
        </div>
      </Form>
    </div>
  )
}
